import os
import time
import logging
import uiautomator2 as u2
from retrying import retry

from src.android.adb.drive import ADB
from src.common.prj_path import get_abs_path
from src.common.utils import get_execute_cmd_result, MyTime, MyPath, get_bounds_center

LOG = logging.getLogger()


class UIAutoControlClass(object):
    def __init__(self, ip, port=5555):
        self.ip = ip
        self.port = port
        self.adb = ADB()
        self.adb.adb_connect(ip, port)
        self.device = u2.connect('{}:{}'.format(self.ip, self.port))
        self.d = self.device.session()

    def click_point(self, x, y):
        if isinstance(x, str):
            x = float(x)
        if isinstance(y, str):
            y = float(y)
        self.d.click(x, y)

    def click_text(self, text):
        self.d(text=text).click()
        time.sleep(0.5)

    def press(self, key, meta=None):
        self.d.press(key, meta)

    def get_all_text(self):
        time.sleep(1)
        all_text = []
        for el in self.d.xpath('//android.view.View').all():
            if el.text:
                all_text.append(el.text)
        LOG.debug('获取到页面文字为={}'.format(all_text))
        return all_text

    def click_edit_text(self):
        all_point = []
        for el in self.d.xpath('//android.widget.EditText').all():
            coord = el.bounds
            all_point.append(get_bounds_center(coord))
        if not all_point:
            raise Exception('not find EditText in this view')
        self.click_point(all_point[-1][0], all_point[-1][1])
        return all_point[-1]

    def wait_element(self, text):
        self.d.xpath(text).wait(timeout=5)
        # self.d.watcher.when(text)

    def screenshot(self):
        save_path = get_abs_path('output', 'screenshot')
        MyPath.make_dirs_if_not_exist(save_path)
        file_name = '{}.jpg'.format(MyTime.format_date_time_1())
        file_path = os.path.join(save_path, file_name)
        cmd = 'uiautomator2 screenshot {}'.format(file_path)
        get_execute_cmd_result(cmd)

    def set_input_text(self, text):
        self.click_edit_text()
        self.d.set_fastinput_ime(True)
        self.d.clear_text()
        self.d.send_keys(text)
        time.sleep(0.5)
        # self.d.send_action("enter")

    def press_button(self, button):
        self.d.press(button)

    def start_app(self, package_name):
        self.d.app_start(package_name)

    def start_activity(self, package_name, activity_name):
        self.d.app_start(package_name, activity_name)

    def click_xpath(self, xpath_string):
        self.d.xpath(xpath_string).click()

    def click_xpath_if_exist(self, xpath_string):
        a = self.d.xpath(xpath_string).all()
        if a:
            self.click_xpath(xpath_string)
            time.sleep(0.5)
        else:
            self.d.press("home")
            time.sleep(0.5)
            self.d.press("back")

    def get_text_count(self, text):
        return self.d(text=text).count

    @retry(wait_fixed=6000, stop_max_attempt_number=10)
    def __check_phone_connected(self):
        try:
            LOG.debug('try to connect {}'.format(self.ip))
            self.adb.adb_connect(self.ip, self.port)
        except Exception as e:
            err_msg = 'connect {} failed, err={}'.format(self.ip, e)
            LOG.error(err_msg)
            raise Exception(err_msg)

    def check_phone_connected(self):
        self.__check_phone_connected()

    def cancel_update(self):
        flag = self.d(text="立即下载").exists(timeout=3)
        if flag:
            self.d(text='取消').click()
            LOG.warning('have update, cancel it!')


if __name__ == '__main__':
    a = UIAutoControlClass('192.168.2.243')
    # a.start_activity('com.taobao.qianniu', '.desktop.ui.MainActivity')
    # a.click_xpath("//android.view.View[contains(@text,'待发货')]")
    # p=a.get_all_text()
    a.start_activity('com.taobao.qianniu', '.desktop.ui.MainActivity')
    # print(a.get_text_count('待发货(2)'))
